package com.bytedance.improvingroad.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import androidx.core.view.ViewCompat
import kotlin.math.abs
import kotlin.properties.Delegates

/**
 * Created by chenxiong
 * date 1/26/22
 */
class DefineDragView @JvmOverloads constructor(
    context: Context,
    attr: AttributeSet? = null,
    style: Int = 0
) : View(context, attr, style) {

    private var mLastX = 0f
    private var mLastY = 0f

    private var mDragSlop by Delegates.notNull<Int>()

    init {
        mDragSlop = ViewConfiguration.get(context).scaledTouchSlop
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when(event.action) {
            MotionEvent.ACTION_MOVE -> {
                val dx = event.x - mLastY
                val dy = event.y - mLastY
                if (abs(dx) > mDragSlop || abs(dy) > mDragSlop) {
                    ViewCompat.offsetTopAndBottom(this, dy.toInt())
                    ViewCompat.offsetLeftAndRight(this, dx.toInt())
                }
            }
        }
        mLastX = event.x
        mLastY = event.y
        return true
    }
}